"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.chatRouter = void 0;
const express_1 = __importDefault(require("express"));
const log4js_1 = require("log4js");
const ChatEntity_1 = require("../entity/ChatEntity");
const logger = (0, log4js_1.getLogger)('route/chat');
function chatRouter(app) {
    const router = express_1.default.Router();
    router.post('/create', async ({ body }, res) => {
        logger.debug('Create room: ' + JSON.stringify(body, null, 2));
        const { roomId, userId } = body;
        let dbChat;
        try {
            dbChat = Object.assign(new ChatEntity_1.ChatEntity(), body);
            logger.debug('chat-room/create: => ', dbChat);
            dbChat.sendTime = Date.now().toString();
            dbChat.lastActiveTime = Date.now().toString();
            dbChat = await dbChat.save();
            res.status(200).send({ result: 'OK', data: dbChat });
        }
        catch (error) {
            logger.debug(error);
            res.status(200).send({ result: 'Error', message: error });
        }
    });
    router.get('/list', async ({ query }, res) => {
        const { roomId, limit = 10, page = 1 } = query;
        logger.debug('chat-room/list: => ', query);
        const data = await ChatEntity_1.ChatEntity.createQueryBuilder('chat')
            .where("chat.roomId=:roomId", { roomId })
            .addOrderBy("sendTime", "DESC")
            .limit(limit)
            .offset(limit * (page - 1))
            .getMany();
        logger.debug('chat-room/list: => ', data);
        res.status(200).send({ result: 'OK', data });
    });
    return router;
}
exports.chatRouter = chatRouter;
